package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.qingcheng.dao.SkuMapper;
import com.qingcheng.dao.StockBackMapper;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.goods.StockBack;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.goods.StockBackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service(interfaceClass = StockBackService.class)
public class StockBackServiceImpl implements StockBackService {

    @Autowired
    private StockBackMapper stockBackMapper;

    /**
     * 添加回滚信息到stockback表中
     * @param orderItemList
     */
    @Override
    @Transactional
    public void addList(List<OrderItem> orderItemList) {
        StockBack stockBack = new StockBack();
        for (OrderItem item : orderItemList) {
            stockBack.setOrderId(item.getOrderId());
            stockBack.setSkuId(item.getSkuId());
            stockBack.setNum(item.getNum());
            stockBack.setCreateTime(new Date());
            stockBack.setStatus("0"); //未回滚
            stockBackMapper.insert(stockBack);
        }
    }

    @Autowired
    private SkuMapper skuMapper;

    @Override
    @Transactional
    public void doBack() {
        System.out.println("回滚开始");
        StockBack stockBack0 = new StockBack();
        stockBack0.setStatus("0");
        List<StockBack> stockBackList = stockBackMapper.select(stockBack0); //找到未回滚的数据
        for (StockBack stockBack : stockBackList) {
            //增加库存
            skuMapper.deductionStock(stockBack.getSkuId(), -stockBack.getNum());
            //减少销售量
            skuMapper.addSaleNum(stockBack.getSkuId(), -stockBack.getNum());
            stockBack.setStatus("1");
            stockBack.setBackTime(new Date());
            stockBackMapper.updateByPrimaryKey(stockBack);
        }
        System.out.println("回滚结束");
    }
}
